//
//  PreorderViewController.swift
//  ShareCar
//
//  Created by lishuai on 2018/6/28.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import UIKit
import MAMapKit
import SnapKit
import AMapSearchKit
import Kingfisher
import AipOcrSdk
import IDLFaceSDK
import TBox
import CoreBluetooth

class PreorderViewController: UIViewController {

    @IBOutlet weak var mapView: MAMapView!
    @IBOutlet var preorderView: UIView!
    @IBOutlet weak var preorderTimeView: UIView!
    
    @IBOutlet var returnCarView: UIView!
    @IBOutlet var dayReturnCarView: UIView!
    @IBOutlet var photoView: UIView!
    
    @IBOutlet weak var carAddressLabel: UILabel!
//    @IBOutlet weak var carDistanceLabel: UILabel!
    
    @IBOutlet weak var returnAddressLabel: UILabel!
    @IBOutlet weak var returnPosLabel: UILabel!
    
    @IBOutlet weak var plateNumberLabel: UILabel!
    @IBOutlet weak var plateNumberLabel2: UILabel!
    @IBOutlet weak var plateNumberLabel3: UILabel!
    
    @IBOutlet weak var carTypeNameLabel: UILabel!
    @IBOutlet weak var carTypeNameLabel2: UILabel!
    @IBOutlet weak var carTypeNameLabel3: UILabel!
    @IBOutlet weak var carImg: UIImageView!
    @IBOutlet weak var carImg2: UIImageView!
    @IBOutlet weak var carImg3: UIImageView!
    
    @IBOutlet weak var whistleButton: GSCountdownButton!
    
    @IBOutlet weak var timerLabel: UILabel!
    @IBOutlet weak var opendoorTimerLabel: UILabel!
    
    @IBOutlet weak var cancelButton: UIButton!
    
    @IBOutlet weak var photoButton: UIButton!
    
    @IBOutlet weak var deadlineLabel: UILabel!
    
    var photoPath: String?
    
    var orderId: String!
    var detail: Order.Detail?
    
    private var location: CLLocation?
    
    var pathPolyLines = [CLLocationCoordinate2D]()
    
    let search = AMapSearchAPI()
    
    var timer: Timer?
    var dayTimer: Timer?
    
    var first = true
    
    var tBox: TBox?
    
    var polyLine: MAPolyline?
    
    /// 是否已验车
    var isCheckCar = false
    
    var centralManager: CBCentralManager?
    var bluetoothState: CBManagerState = .unknown
    
    @IBOutlet weak var durationView: UIView!
    
    @IBOutlet weak var durationButton: UIButton!
    
    //保留时间
    var retentionTime = 15 * 60
    
    let loading = LoadingTitle()
    let vc = LivenessViewController()
    
    // MARK: - view
    
    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.config()
        mapView.delegate = self
        
        search?.delegate = self
        
        centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.global())
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        navigationController?.isNavigationBarHidden = false
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        navigationController?.isNavigationBarHidden = true
        loadOrder()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        if isCheckCar {
            openDoor()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    deinit {
        timer?.invalidate()
        timer = nil
        
        dayTimer?.invalidate()
        dayTimer = nil
    }
    
    // MARK: - custom method
    
    func openDoor() {
        
        func living() {
            
            vc.delegate = self
            if let model = LivingConfigModel.sharedInstance() {
                model.numOfLiveness = 1
                vc.livenesswithList(model.liveActionArray as? [Any],
                                    order: model.isByOrder,
                                    numberOfLiveness: model.numOfLiveness,
                                    and:self,
                                    andType: 1)
                isCheckCar = false
                present(vc, animated: true, completion: nil)
            }
        }
        
        guard bluetoothState == .poweredOn else {
            alert(message: "蓝牙连接失败，请您确认蓝牙已开启，如开启请靠近车辆在重新尝试(1040)")
            return
        }
        
        loading.show()
        if let t = tBox {
            t.auth(success: { [weak self] in
                self?.loading.hide()

                t.disconnect()

                if UserDefaults.standard.bool(forKey: "showGuidePage") {
                    living()
                } else {
                    if let vc = UIStoryboard(name: "UserInfo", bundle: nil).instantiateViewController(withIdentifier: "faceControllerSence") as? FaceGuideViewController {
                        self?.isCheckCar = false
                        vc.orientation = 1
                        vc.block = { living() }
                        self?.navigationController?.pushViewController(vc, animated: true)
                    }
                }
            }) { [weak self] msg in
                t.disconnect()
                self?.loading.hide()
                self?.showError(msg)
            }
        }
    }
    
    func loadOrder() {
        Order.detail(orderId: self.orderId, location: self.userLocation, success: { [weak self] data in
            self?.detail = data
            
            self?.showBottomView()
            self?.addAnnotations()
            self?.walkingRouts()
            
            if let name = data?.bluetoothName, let sn = data?.bluetoothSn, let code = data?.tboxDeviceCode {
                if let type = TBoxType(rawValue: code) {
                    self?.tBox = TBox(type: type, name: name, password: sn)
                }
            } else {
                p("未取得bluetooth_name与bluetooth_sn")
            }
        }) { [weak self] error in
            self?.showError(error)
        }
    }
    
    //规划步行路线
    func walkingRouts() {
        guard let car = self.detail else {
            return
        }
        
        guard let userLoc = self.mapView.userLocation else {
            return
        }
        
        self.mapView.removeOverlays(self.mapView.overlays)
        
        if let lat = CLLocationDegrees(car.carLat),
            let lng = CLLocationDegrees(car.carLng),
            let user = userLoc.location {
            let start = user.coordinate
            let destination = CLLocationCoordinate2D(latitude: lat, longitude: lng)
            
            let request = AMapWalkingRouteSearchRequest()
            request.origin = AMapGeoPoint.location(withLatitude: CGFloat(start.latitude),
                                                   longitude: CGFloat(start.longitude))
            request.destination = AMapGeoPoint.location(withLatitude: CGFloat(destination.latitude),
                                                        longitude: CGFloat(destination.longitude))
            
            search?.aMapWalkingRouteSearch(request)
        }
    }
    
    func showPhotoView() {
        view.addSubview(photoView)
        photoView.bringSubview(toFront: self.view)
        
        photoView.snp.makeConstraints { (make) -> Void in
            make.left.right.top.bottom.equalTo(0)
        }
    }
    
    func showBottomView() {
        guard let detail = self.detail else {
            showError("无订单详情")
            return
        }
        
        if detail.orderStatus == Order.Status.reserve {
            showPreorderView()
        } else if detail.orderStatus == Order.Status.use {
            if detail.orderType == 1 {
                showReturnCarView()
                cancelButton?.removeFromSuperview()
            } else {
                if detail.opendoorFlag == 0 {
                    showPreorderView()
                    cancelButton.setTitle("直接还车", for: .normal)
                } else {
                    showReturnCarView()
                    cancelButton?.removeFromSuperview()
                }
            }
        } else {
            navigationController?.popViewController(animated: true)
        }
    }
    
    func showPreorderView() {
        returnCarView.removeFromSuperview()
        view.addSubview(preorderView)
        
        if let detail = detail {
            if detail.orderType == 2 {
                preorderTimeView.isHidden = true
            } else {
                retentionTime = (detail.retentionTime + 15) * 60
                timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in
                    guard let self = self else {
                        return
                    }

                    DispatchQueue.global().async {
                        let now = Date().timeIntervalSince1970
                        var time = Int(now) - detail.orderTime
                        time = time < 0 ? 0 : time
                        let m = time / 60 > 9 ? "\(time / 60)" : "0\(time / 60)"
                        let s = time % 60 > 9 ? "\(time % 60)" : "0\(time % 60)"
                        
                        DispatchQueue.main.async {
                            self.timerLabel.text = "\(m):\(s)"
                            if detail.orderTime + self.retentionTime < Int(now) {
                                Order.cancelPreorder(orderId: detail.orderId, reason: "超时取消", location: nil, success: { data in
                                    self.timer?.invalidate()
                                    self.timer = nil
                                }, failure: { msg in
                                    self.timer?.invalidate()
                                    self.timer = nil
                                })
                                self.navigationController?.popViewController(animated: true)
                            }
                        }
                    }
                }
            }
            
            plateNumberLabel.text = detail.carPlateNumber
            carTypeNameLabel.text = detail.carTypeName
            let url = URL(string: kImageServerName + detail.carImg)
            carImg.kf.setImage(with: url)
            carAddressLabel.text = detail.carAddress
            
            returnAddressLabel.text = "停车位置：" + detail.returnAddress
            
            switch detail.returnPos {
            case 1:
                returnPosLabel.text = "车位信息：地面"
            case 2:
                returnPosLabel.text = "车位信息：地下"
            case 3:
                returnPosLabel.text = "车位信息：停车楼"
            default:
                returnPosLabel.text = "车位信息：未知"
            }
        }
        
        self.preorderView.snp.makeConstraints { (make) -> Void in
            make.bottom.equalTo(-35)
            make.height.equalTo(295)
            make.width.equalTo(330)
            make.centerX.equalTo(self.view.snp.centerX)
        }
    }
    
    func showReturnCarView() {
        preorderView.removeFromSuperview()
        
        if let detail = detail {
            if detail.orderType == 1 {  //分时
                view.addSubview(returnCarView)
                dayReturnCarView.removeFromSuperview()
                showShareReturnCarView(detail: detail)
            } else if detail.orderType == 2 {   //日租
                view.addSubview(dayReturnCarView)
                returnCarView.removeFromSuperview()
                showDayReturnCarView(detail: detail)
            }
        }
    }
    
    func showShareReturnCarView(detail: Order.Detail) {
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in
            
            let now = Date().timeIntervalSince1970
            var time = Int(now) - detail.opendoorTime
            
            time = time < 0 ? 0 : time
            let h = time / 3600
            let m = (time - h * 3600) / 60 > 9 ? "\((time - h * 3600) / 60)" : "0\((time - h * 3600) / 60)"
            let s = time % 60 > 9 ? "\(time % 60)" : "0\(time % 60)"
            
            self?.opendoorTimerLabel.text = "\(h):\(m):\(s)"
        }
        
        plateNumberLabel2.text = detail.carPlateNumber
        carTypeNameLabel2.text = detail.carTypeName
        let url = URL(string: kImageServerName + detail.carImg)
        carImg2.kf.setImage(with: url)
        
        let name = detail.durationPackageName
        
        if name.count > 0 {
            durationButton?.setTitle(name, for: .normal)
        } else {
            durationButton?.setTitle("选择", for: .normal)
        }
        
        self.returnCarView.snp.makeConstraints { (make) -> Void in
            make.bottom.equalTo(-30)
            make.height.equalTo(355)
            make.width.equalTo(330)
            make.centerX.equalTo(self.view.snp.centerX)
        }
        
        if detail.isUseableDurationPackage != 1 {
            durationView.isHidden = true
        }
    }
    
    func showDayReturnCarView(detail: Order.Detail) {
        let now = Int(Date().timeIntervalSince1970)
        let time = TimeInterval(300 - (now - detail.opendoorTime))
        
        if time > 0 && detail.isUploadOil == 0 {
            showPhotoView()

            dayTimer = Timer.scheduledTimer(withTimeInterval: time, repeats: false) { [weak self] _ in
                self?.photoView.removeFromSuperview()
                
                self?.dayTimer?.invalidate()
                self?.dayTimer = nil
            }
        }
        
        plateNumberLabel3.text = detail.carPlateNumber
        carTypeNameLabel3.text = detail.carTypeName
        let url = URL(string: kImageServerName + detail.carImg)
        carImg3.kf.setImage(with: url)
        
        deadlineLabel.text = "预计租期: "
            + timeStampToString(timeStamp: detail.preStartTime)
            + " - "
            + timeStampToString(timeStamp: detail.preEndTime)

        self.dayReturnCarView.snp.makeConstraints { (make) -> Void in
            make.bottom.equalTo(0)
            make.height.equalTo(275)
            make.width.equalTo(330)
            make.centerX.equalTo(self.view.snp.centerX)
        }
    }
    
    func timeStampToString(timeStamp:Int)->String {
        let timeSta = TimeInterval(timeStamp)
        let dfmatter = DateFormatter()
        dfmatter.dateFormat = "yyyy/MM/dd HH:mm"
        let date = Date(timeIntervalSince1970: timeSta)
        return dfmatter.string(from: date)
    }
    
    func addAnnotations() {
        let ann = MAPointAnnotation()
        if let car = detail,
            let lat = CLLocationDegrees(car.carLat),
            let lng = CLLocationDegrees(car.carLng) {
            let loc = CLLocationCoordinate2D(latitude: lat, longitude: lng)
            ann.coordinate = loc
            mapView.addAnnotation(ann)
        }
    }
    
    // MARK: - IBAction
    
    @IBAction func openDoorAction(_ sender: UIButton) {
        if detail?.checkFlag == 1 {
            performSegue(withIdentifier: "checkCarSegue", sender: nil)
        } else {
            openDoor()
        }
    }
    
    @IBAction func whistleAction(_ sender: Any) {
        JZLoading.showLoadingWith(toView: self.view)
        Order.whistle(orderId: self.orderId, location: self.userLocation, success: { [weak self] in
            JZLoading.hideLoading()
            XHProgressHUD.showSuccess("鸣笛成功")
            
            self?.whistleButton.maxSecond = 5
            self?.whistleButton.countdown = true
            self?.whistleButton.borderColor = UIColor(valueRGB: 0xDDDDDD, alpha: 1.0)
            self?.whistleButton.backgroundColor = UIColor(valueRGB: 0xDDDDDD, alpha: 1.0)
            
            self?.whistleButton.stopedBlock = {
                self?.whistleButton.borderColor = UIColor(valueRGB: 0xfca648, alpha: 1.0)
                self?.whistleButton.backgroundColor = UIColor(valueRGB: 0xffffff, alpha: 1.0)
            }
        }) { [weak self] error in
            JZLoading.hideLoading()
            self?.showError(error)
        }
    }
    
    @IBAction func addTime(_ sender: UIButton) {
        JZLoading.showLoadingWith(toView: self.view)
        Order.addTime(orderId: self.orderId, location: self.userLocation, success: { [weak self] data in
            if let data = data {
                JZLoading.hideLoading()
                self?.retentionTime = 75 * 60
                self?.alert(title: "提示", message: data["message"] ?? "现已为您加时至75分钟，其中： 0－15分钟  免费,15－30分钟   1元／分钟,30分钟以上   2元／分钟(不满1分钟按1分钟计时),最终费用以计时器为准。")
            }
        }) { [weak self] error in
            JZLoading.hideLoading()
            self?.showError(error)
        }
    }
    
    @IBAction func openDoor2(_ sender: UIButton) {
        
        guard bluetoothState == .poweredOn else {
            alert(message: "蓝牙连接失败，请您确认蓝牙已开启，如开启请靠近车辆在重新尝试(1040)")
            return
        }
        
        guard let t = self.tBox else {
            return
        }
        
        func bluetoothOpenDoor() {
            JZLoading.showLoadingWith(toView: self.view)
            t.auth(success: { [weak self] in
                t.unLock({ success, finish, message in
                    t.disconnect()
                    if success {
                        JZLoading.hideLoading()
                        self?.showError("开门成功")
                    } else {
                        if finish {
                            JZLoading.hideLoading()
                            self?.showError("开门失败")
                        }
                    }
                })
            }) { [weak self] msg in
                t.disconnect()
                JZLoading.hideLoading()
                self?.showError(msg)
            }
        }
        
        func tboxOpenDoor() {
            JZLoading.showLoadingWith(toView: self.view)
            t.auth(success: { [weak self] in
                t.disconnect()
                guard let self = self else {
                    return
                }
                
                Order.openDoor(orderId: self.orderId, location:self.userLocation, success: {
                    JZLoading.hideLoading()
                    self.showError("开门成功")
                }, failure: { error in
                    JZLoading.hideLoading()
                    if error.code == 2002 || error.code == 0 {
                        bluetoothOpenDoor()
                    } else {
                        self.showError(error)
                    }
                })
            }, failure: { [weak self] msg in
                t.disconnect()
                JZLoading.hideLoading()
                self?.showError(msg)
            })
        }
        
        tboxOpenDoor()
    }
    
    @IBAction func returnCar(_ sender: UIButton) {
        guard self.orderId != nil else {
            self.showError("订单id错误")
            return
        }
        
        guard let loc = self.location?.coordinate else {
            self.showError("请您确认打开定位后重新尝试(1029)")
            return
        }
        
        JZLoading.showLoadingWith(toView: self.view)
        Order.returnCar(orderId: orderId, location: loc, success: { [weak self] data in
            JZLoading.hideLoading()
            guard let data = data else {
                return
            }
            
            guard data.distance == 0 else {
                self?.alert(message: "抱歉，蜜橙出行暂不支持外埠还车，请您将车辆归还至原取车城市内，感谢您的配合！")
                return
            }
            
            switch data.type {
            case .charge:
                let alert = UIAlertController(title: nil, message: "您当前位置是收费区，将产生停车附加费，附近有0元停车区，您可以查看并决定是否前往", preferredStyle: .alert)
                
                alert.addAction(UIAlertAction(title: "查看0元停车区", style: .default) { action in
                    self?.performSegue(withIdentifier: "returnCarSegue", sender: data)
                })
                
                alert.addAction(UIAlertAction(title: "就地停放", style: .default) { action in
                    if self?.detail?.orderType == 1 {
                        self?.performSegue(withIdentifier: "confirmReturnCarSegue", sender: nil)
                    } else {
                        self?.performSegue(withIdentifier: "oilRecordSegue", sender: nil)
                    }
                })
                
                self?.present(alert, animated: true, completion: nil)
            case .free:
                if self?.detail?.orderType == 1 {
                    self?.performSegue(withIdentifier: "confirmReturnCarSegue", sender: nil)
                } else {
                    self?.performSegue(withIdentifier: "oilRecordSegue", sender: nil)
                }
            }
            
        }) { [weak self] error in
            JZLoading.hideLoading()
            if error.code == 1014 || error.code == 1015 || error.code == 1017 || error.code == 1018 {
                self?.alert(message: error.msg)
            } else {
                self?.showError(error)
            }
        }
    }
    
    @IBAction func doubleFlicker(_ sender: GSCountdownButton) {
        JZLoading.showLoadingWith(toView: self.view)
        Order.doubleFlicker(orderId: orderId, location: userLocation, success: { [weak self] in
            JZLoading.hideLoading()
            self?.showError("双闪成功")
            
            sender.maxSecond = 5
            sender.countdown = true
            sender.borderColor = UIColor(valueRGB: 0xDDDDDD, alpha: 1.0)
            sender.backgroundColor = UIColor(valueRGB: 0xDDDDDD, alpha: 1.0)
            
            sender.stopedBlock = {
                sender.borderColor = UIColor(valueRGB: 0xfca648, alpha: 1.0)
                sender.backgroundColor = UIColor(valueRGB: 0xffffff, alpha: 1.0)
            }
        }) { [weak self] error in
            JZLoading.hideLoading()
            self?.showError(error)
        }
    }
    
    func bluetoothCloseDoor() {
        guard bluetoothState == .poweredOn else {
            alert(message: "蓝牙连接失败，请您确认蓝牙已开启，如开启请靠近车辆在重新尝试(1040)")
            return
        }
        
        JZLoading.showLoadingWith(toView: self.view)
        
        guard let t = self.tBox else {
            return
        }
        
        t.auth(success: { [weak self] in
            t.lock({ success, finish, message in
                t.disconnect()
                if success {
                    JZLoading.hideLoading()
                    self?.showError("锁门成功")
                } else {
                    if finish {
                        JZLoading.hideLoading()
                        self?.showError("锁门失败！请关闭车灯、熄火、关闭车门后重试。")
                    }
                }
            })
        }) { [weak self] msg in
            t.disconnect()
            JZLoading.hideLoading()
            self?.showError("锁门失败！请关闭车灯、熄火、关闭车门后重试。")
        }
    }
    
    func httpCloseDoor() {
        JZLoading.showLoadingWith(toView: self.view)
        Order.lockDoor(orderId: orderId, location: userLocation, success: { [weak self] in
            JZLoading.hideLoading()
            self?.showError("锁门成功")
        }) { [weak self] message in
            JZLoading.hideLoading()
            if message.code == 2003 || message.code == 0 {
                self?.bluetoothCloseDoor()
            } else {
                self?.showError("锁门失败！请关闭车灯、车辆熄火、确定档位至P档、拉起手刹、关闭车门后重试。")
            }
        }
    }
    
    @IBAction func lockCar(_ sender: UIButton) {
        let k = LockAlertViewController.kNoShowLockAlert
        if !UserDefaults.standard.bool(forKey: k) {
            performSegue(withIdentifier: "lockAlert", sender: nil)
        } else {
            httpCloseDoor()
        }
    }
    
    @IBAction func back(_ sender: UIButton) {
        navigationController?.popViewController(animated: true)
    }
    
    @IBAction func cancel(_ sender: UIButton) {
        if detail?.orderType == 1 { //分时，取消订单
            let now = Date().timeIntervalSince1970
            if let orderTime = detail?.orderTime {
                if Int(now) - orderTime > 15 * 60 {
                    alertWithCancelButton(message: "当前订单已产生加时预约费用，是否取消") { [weak self] in
                        self?.performSegue(withIdentifier: "cancelSegue", sender: nil)
                    }
                } else {
                    performSegue(withIdentifier: "cancelSegue", sender: nil)
                }
            }
        } else if detail?.orderType == 2 {  //日租，直接还车
            alertWithCancelButton(title: nil, message: "直接还车后将按照还车时间计算费用，是否直接还车？") { [weak self] in
                guard let self = self else {
                    return
                }
                guard let orderId = self.detail?.orderId else {
                    return
                }
                guard let loc = self.userLocation else {
                    return
                }
                JZLoading.showLoadingWith(toView: self.view)
                Order.straightReturnCar(orderId: orderId, location: loc, success: { [weak self] in
                    JZLoading.hideLoading()
                    self?.performSegue(withIdentifier: "dayReturnDetailSegue", sender: orderId)
                }) { [weak self] msg in
                    self?.showError(msg)
                }
            }
        }
    }
    
    @IBAction func more(_ sender: UIButton) {
        performSegue(withIdentifier: "moreSegue", sender: nil)
    }
    
    @IBAction func navigator(_ sender: UIButton) {
        
        var lat: Double = 0.0
        var lon: Double = 0.0
        
        if let car = self.detail {
            lat = Double(car.carLat)!
            lon = Double(car.carLng)!
        }
        
        let array = Navigator.installApps()

        let actionSheet = UIAlertController(title: "选择导航软件", message: "", preferredStyle: .actionSheet)
        
        actionSheet.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { [weak self] action in
            self?.dismiss(animated: true, completion: nil)
        }))
        
        for item in array {
            actionSheet.addAction(UIAlertAction.init(title: item.name, style: .default, handler: { action in
                switch item.index {
                case 0:
                    Navigator.gotoBaiduApp(lat, lon: lon)
                case 1:
                    Navigator.gotoGaodeApp(lat, lon: lon )
                case 2:
                    Navigator.gotoSystemMap(lat, lon: lon)
                default:break
                }
            }))

        }
        present(actionSheet, animated: true, completion: nil)
    }
    
    @IBAction func photo(_ sender: UIButton) {
        #if DEBUG
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.allowsEditing = true
            picker.sourceType = .camera
            self.present(picker, animated: true, completion: nil)
        } else {
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
                let picker = UIImagePickerController()
                picker.delegate = self
                picker.allowsEditing = true
                picker.sourceType = .photoLibrary
                self.present(picker, animated: true, completion: nil)
            } else {
                p("读取相册失败")
            }
        }
        #else
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.allowsEditing = true
            picker.sourceType = .camera
            present(picker, animated: true, completion: nil)
        } else {
            showError("不支持拍照")
        }
        #endif
    }
    
    @IBAction func submitPhoto(_ sender: UIButton) {
        guard let id = detail?.orderId else {
            showError("订单号错误")
            return
        }
        
        guard let img = photoPath else {
            showError("未拍照")
            return
        }
        
        Order.openDoorUploadBoardImg(orderId: id, boardImg: img, success: { [weak self] in
            self?.photoView.removeFromSuperview()
            
            self?.dayTimer?.invalidate()
            self?.dayTimer = nil
        }) { [weak self] msg in
            self?.showError(msg)
        }
    }
    
    // MARK: - Navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "cancelSegue" {
            if let vc = segue.destination as? CancelViewController {
                vc.orderId = orderId
                vc.orderTime = detail?.orderTime
            }
        } else if segue.identifier == "moreSegue" {
            if let vc = segue.destination as? MoreViewController {
                vc.order = detail
            }
        } else if segue.identifier == "returnCarSegue" {
            if let vc = segue.destination as? ReturnCarViewController {
                vc.order = detail
                vc.location = location
                vc.stopPoint = sender as? Order.ReturnCar
                if let carPlateNumber = detail?.carPlateNumber {
                    vc.carPlateNumber = carPlateNumber
                }
            }
        } else if segue.identifier == "confirmReturnCarSegue" {
            if let vc = segue.destination as? ConfirmReturnCarViewController {
                vc.order = detail
                vc.location = location
//                if let carPlateNumber = detail?.carPlateNumber {
//                    vc.carPlateNumber = carPlateNumber
//                }
            }
        } else if segue.identifier == "durationPackageSegue" {
            if let vc = segue.destination as? DurationPackageListViewController {
                vc.orderId = detail?.orderId
                vc.projectTimerentId = detail?.projectTimerentId
                vc.selectedDurationPackageId = detail?.durationPackageId
                vc.sourceFlag = 2
            }
        } else if segue.identifier == "webViewSence" {
            if let nav = segue.destination as? UINavigationController,
                let vc = nav.viewControllers.first as? WebViewController {
                vc.page = Page.server(.refuel)
            }
        } else if segue.identifier == "checkCarSegue" {
            if let vc = segue.destination as? CheckCarViewController {
                vc.orderId = detail?.orderId
            }
        } else if segue.identifier == "oilRecordSegue" {
            if let vc = segue.destination as? OilRecordViewController {
                vc.order = detail
                vc.location = location
            }
        } else if segue.identifier == "dayReturnDetailSegue" {
            if let vc = segue.destination as? DayReturnDetailViewController {
                vc.orderId = detail?.orderId
            }
        } else if segue.identifier == "lockAlert" {
            if let vc = segue.destination as? LockAlertViewController {
                vc.completion = { [weak self] in
                    self?.httpCloseDoor()
                }
            }
        }
    }
}

// MARK: - MAMapViewDelegate

extension PreorderViewController: MAMapViewDelegate {
    
    func mapView(_ mapView: MAMapView!, didUpdate userLocation: MAUserLocation!, updatingLocation: Bool) {
        if updatingLocation && first {
            if let location = userLocation.location {
                self.location = location
                loadOrder()
                first = false
            }
        }
    }
    
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        
        let carIndetifier = "carIndetifier"
        
        if annotation is MAUserLocation {
            return nil
        }
        
        if annotation is MAPointAnnotation {
            var annotationView: MAAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: carIndetifier)
            
            if annotationView == nil {
                annotationView = MAAnnotationView(annotation: annotation, reuseIdentifier: carIndetifier)
            }
            
            annotationView!.image = UIImage(named: "restaurant")
            annotationView!.centerOffset = CGPoint(x: 0, y: -24)
            
            return annotationView!
        }
        
        return nil
    }
    
    func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
        let lineColor = UIColor(red: 255.0 / 255.0, green: 117.0 / 255.0, blue: 23.0 / 255.0, alpha: 1.0)
        if overlay is MAPolyline {
            
            guard let polyline = MAPolylineRenderer(overlay: overlay) else {
                return nil
            }
            
            polyline.lineDashType = .square
            polyline.lineWidth = 5.0
            polyline.strokeColor = lineColor
            polyline.fillColor = lineColor
            polyline.lineJoinType = kMALineJoinRound
            polyline.lineCapType = kMALineCapRound
            
            return polyline
        }
        
        return nil
    }
}

// MARK: - AMapSearchDelegate

extension PreorderViewController: AMapSearchDelegate {
    
    func onRouteSearchDone(_ request: AMapRouteSearchBaseRequest!, response: AMapRouteSearchResponse!) {
        if response.count > 0 {
            
            pathPolyLines.removeAll()
            
            let path = response.route.paths.first
            for step in (path?.steps)! {
                let polyline = step.polyline
                let loc = polyline?.components(separatedBy: ";")
                if let loc = loc {
                    for i in loc {
                        let lays = i.components(separatedBy: ",")
                        let lat = CLLocationDegrees(lays[1])
                        let lng = CLLocationDegrees(lays[0])
                        let location = CLLocationCoordinate2D(latitude: lat!, longitude: lng!)
                        pathPolyLines.append(location)
                    }
                }
            }
            
            if let poly = MAPolyline(coordinates: &pathPolyLines, count: UInt(pathPolyLines.count)) {
                //全局变量保存这个值，后续删除
                polyLine = poly
                
                mapView.add(poly)
                let insets = UIEdgeInsets(top: 40, left: 40, bottom: preorderView.frame.height + 40, right: 40)
                mapView.showOverlays([poly], edgePadding: insets, animated: true)
            }
        }
    }
}

// MARK: - FaceDelegate

extension PreorderViewController: FaceDelegate {
    func send(_ image: UIImage!) {
        DispatchQueue.global().async { [weak self] in
            guard let self = self else {
                return
            }
            
            let imgData = image.compress(maxSizeKBytes: kMaxSizeKBytes)
            DispatchQueue.main.async {
                self.loading.show()
                Order.openDoor(orderId: self.orderId, faceImg: imgData, location: self.userLocation, success: {
                    self.loading.hide()
                    self.showError("开门成功")
                    
                    //第一次开门成功以后清除之前的路线规划路劲
                    self.mapView.remove(self.polyLine)
                    
                    self.loadOrder()
                }, failure: { error in
                    self.loading.hide()
                    self.showError(error)
                })
                
                self.vc.dismiss(animated: true)
            }
        }
    }
}

// MARK: - CBCentralManagerDelegate

extension PreorderViewController: CBCentralManagerDelegate {
    public func centralManagerDidUpdateState(_ central: CBCentralManager) {
        bluetoothState = central.state
    }
}

extension PreorderViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerEditedImage] as! UIImage
        
        DispatchQueue.global().async { [weak self] in
            guard let self = self else {
                return
            }
            
            let imgData = image.compress(maxSizeKBytes: kMaxSizeKBytes)
            DispatchQueue.main.async {
                let file = HTTPRequest.File(data: imgData,
                                            name: "image_path",
                                            fileName: "file.jpg",
                                            mimeType: "image/jpg")
                
                JZLoading.showLoadingWith(toView: self.view)
                File.upload(file: file, success: { data in
                    JZLoading.hideLoading()
                    self.photoButton.setImage(image, for: .normal)
                    self.photoPath = data?.imagePath
                }) { error in
                    JZLoading.hideLoading()
                    self.showError(error)
                }
                self.dismiss(animated: true)
            }
        }
    }
}
